/*
 * 树形组件
 */
;(function($){
	
	//模板和静态html，用于生成树形结构
	var Temp={
			beSelected:'<span class="name_selected" val={{id}}>{{name}}</span>',
			branches:'<ul class="branches">{{if hasLeaves}} <li val=-1><label><span>全选</span></label></li>{{/if}}'
				+    '{{each}}<li val={{$value.id}}><span>{{$value.name}}</span><span class="count">{{$value.totalLeaves}}</span></li>{{/each}}'
				+    '</ul>',
			leaves:'<ul class="leaves">'
				+    '{{each}}<li val={{$value.id}} ><label {{if $value.beChoosed}} class="choosed" {{/if}}><img src={{$value.photo}}/><span>{{$value.name}}</span></label></li>{{/each}}'
				+    '<ul>'
	},
	Html={
			start:"<div class='tree'>",
			search:'<div class="search"><i class=""></i><input type="text" /></div>',
			selected:'<div class="selected"><span>已选择：</span><span class="open">开</span></div>',
			content:'<div class="content"><div class="active" data-transition="slide"><div>',
			end:"</div></div><div data-transition='slide'><div></div></div></div></div>"
		};
	/**
	 * @description 树形构造器
	 * @constructor
	 */
	function Tree(cfg){
		
		this.$tree=null;//jquery对象
		this.tree=null;//树形结构的数据
		this.leaves=[];//所有叶子节点，===tree里面的叶子
		
		this.curBranch=null;//当前显示的节点
		this.selected=[];//当前选中的叶子节点
		
		this.onBranchSelect=cfg.onBranchSelect;//选择一个节点的回调
		
		for(var i in Temp ){
			if(cfg.hasOwnProperty(i)){
				Temp[i]=cfg[i];
			}
		};
		for(var i in Html ){
			if(cfg.hasOwnProperty(i)){
				Html[i]=cfg[i];
			}
		};
		//初始化
		this.initData(cfg.DepartList,cfg.EmployeeList);
		this.initHtml(cfg.selector);
		this.initEvent();
	};
	
	/**
	 *@description 生成树形结构数据 this.tree
	 */
	Tree.prototype.initData=function(branches,leaves){
		var trunk = branches.shift(),
			_leaves=this.leaves;
			
		this.tree={
			id: trunk.ID.toLowerCase(),
			name: trunk.Name
//			branches:null,//有子节点的枝干
//			leaves:null, //叶子节点
//			totalLeaves:0//包含的叶子总数
		};
		appendNode(this.tree,0);
		
		function appendNode(parent,index) {
			var pid = parent.id.toLowerCase(),
				arr;
				
				//添加叶子节点
				arr = parent.leaves = [];
				for (var m = leaves.length-1; m>-1; m--) {
					var item = leaves[m];
					if (item.DepartID === pid) {
						var leaf = {
							id: item.ID,
							name: item.Name
						}
						arr.push(leaf);
						_leaves.push(leaf);
						leaves.splice(m, 1);//去掉已经添加的叶子节点
					}
				};
				parent.totalLeaves=arr.length;
				parent.hasLeaves=(arr.length>0);
				//添加节点 
				arr = parent.branches = [];
				//数据排序是父节点在上子节点在下的数组
				for (var i = index, m = branches.length; i < m; i++) {
					var item = branches[i];
					try {
						if (item.PID.toLowerCase() === pid) { //如果有子节点
							var branch = {
								id: item.ID,
								name: item.Name
							};
							
							//从当前节点往下寻找子节点
							branches.splice(i, 1);
							appendNode(branch, i--);
							
							parent.totalLeaves+=branch.totalLeaves;
							arr.push(branch);
						} else { //没有子节点
							return;
						}
					} catch (e) {
						i = 0;
						m = branches.length;
					}
				};
			}
	}

	/**
	 * @description 生成this.$tree，添加到页面
	 */
	Tree.prototype.initHtml=function (selector){
		//初始化页面结构
		this.$tree=$(Html.start+Html.search+Html.selected+Html.content
		+    this.getContent(this.tree.id)
		+    Html.end);
		$(selector).append(this.$tree);
		this.checkIsAll();
	};
	/**
	 * @description 生成内容的 html
	 */
	Tree.prototype.getContent=function(id){
		
		var html="",
			render;
			
		if(id){
			this.curBranch=_getBranchById(this.tree,id);
			console.log(this.curBranch);
			this.onBranchSelect&&(this.onBranchSelect(this.curBranch));
		}
		//是否叶子
		this.curBranch.branches.hasLeaves=this.curBranch.hasLeaves;
		
		render=template.compile(Temp.branches);
		html+=render(this.curBranch.branches);
		
		if(this.curBranch.leaves.length){
			render=template.compile(Temp.leaves);
			html+=render(this.curBranch.leaves);
		}
		
		return html;
	}
	/**
	 * @description 检查当前braches 是否全部被选中
	 */
	Tree.prototype.checkIsAll=function(){
		var leaves=this.curBranch.leaves;
		if(leaves.length){
			var all=true;
			leaves.forEach(function(item){
				if(!item.beChoosed){
					all=item.beChoosed;
				}
			});
			this.$tree.find(".branches label")[all?"addClass":"removeClass"]("choosed");
		}
	}
	
	/**
	 * @description 根据部门id，获取部门信息
	 */
	function _getBranchById (par,id) {
		if(par.id===id){
			return par;
		};
		var n;
		for (var i=0,j=par.branches.length;i<j;i++) {
			//递归查找
			if(n=_getBranchById(par.branches[i],id)){
				return n;
			};
		};
		return n;
	}
	/**
	 * @description 初始化搜索，员工和部门的事件
	 */
	Tree.prototype.initEvent=function(){
		var that=this;
		//输入查询事件
		this.$tree.find(".tree .search input").on("input",function(){
			var search=$(this).val();
			if(search){
				//根据搜索关键字，在所有叶子节点上查找
				var leaves=that.leaves;
				var result=[];
				for (var i=0,j=leaves.length;i<j;i++) {
					if(leaves[i].name.indexOf(search)!=-1){
						result.push(leaves[i]);
					}
				};
				var render=template.compile(Temp.leaves);
				that.$tree.find(".content>.active>div").html(render(result));
			}else{
				//还原到当前选择的枝干上
				that.$tree.find(".content>.active>div").html(that.getContent());
				that.checkIsAll();
			}
		});
		//点击查看枝干
		this.$tree.on("click",".branches li",function(ev){
			var $li=$(this);
			var id=$li.attr("val");
			if(id!=-1){
				//页面转换
				var $current=that.$tree.find(".content>.active"),
					$target=$current.siblings();
				$target.children("div").html(that.getContent(id));
				J.Transition.run($current,$target)
				that.checkIsAll();
			}else{
				//全选
				var $label=$li.children("label");
				var isChoosed=!$label.hasClass("choosed");
				var $name,
					$selected=$li.closest(".tree").find(".selected");
//					selected=that.selected;
					
				that.curBranch.leaves.forEach(function(item){
					var leaf={
						id:item.id,
						name:item.name
					};
					if(isChoosed&&!item.beChoosed){
						$name=_getNameSpan(leaf);
						$selected.append($name);
					};
					if(isChoosed!==item.beChoosed){
						that.setLeafChoosed(leaf,isChoosed,$name);
					};
				});
				$label.toggleClass("choosed");
//				var hasamount=selected.length>0;
//				$selected[hasamount?"addClass":"removeClass"]("hasamount")
			}
		});
		//选择一个叶子
		this.$tree.on("click",".leaves li",function(){
			console.log("choose leaves");
			
			var $li=$(this);
			var id=$li.attr("val")
				name=$li.find("span").text();
			var $label=$(this).children("label"),
				$name,
				$selected=$li.closest(".tree").find(".selected"),
				leaf={
					id:id,
					name:name
				};
//				selected=that.selected;
				
			var choosed=!$label.hasClass("choosed");
			if(choosed){
				//生成span
				$name=_getNameSpan(leaf);
				$selected.append($name);
			}
			that.setLeafChoosed(leaf,choosed,$name);
		
//			var hasamount=selected.length>0;
//			$selected[hasamount?"addClass":"removeClass"]("hasamount");
			that.checkIsAll();
		});
		//移除选中的叶子
		this.$tree.on("click",".selected>.name_selected",function(){
			var leaf={
				id:$(this).attr("val"),
				name:$(this).text()
			}
			that.setLeafChoosed(leaf,false);
//			var hasamount=that.selected.length>0;
//			that.$tree.find(".selected")[hasamount?"addClass":"removeClass"]("hasamount");
			that.checkIsAll();
		});
		//查看完整选中的叶子
		this.$tree.on("click",".selected>.open",function(){
			$(this).parent().toggleClass("open")
		});
	}
	
	/**
	 *@description 生成选中的名字的span
	 */
	function _getNameSpan(leaf){
		var render=template.compile(Temp.beSelected);
		return $(render(leaf));
	}
	/**
	 * @description 设置叶子的状态
	 */
	Tree.prototype.setLeafChoosed=function(leaf,choosed,$name){
		var that=this,
			selected=this.selected,
			id=leaf.id;
		if(choosed){
			selected.push(leaf);
		}else{
			for (var i=0,j=selected.length;i<j;i++) {
				if(selected[i].id===id){
					selected.splice(i,1);
					break;
				};
			};
		};
		this.leaves.forEach(function(leaf){
			if(leaf.id===id){
				leaf.beChoosed=choosed;
				if((!choosed)&&leaf.$name){
					leaf.$name.remove();
				};
				leaf.$name=$name;
				that.$tree.find("[val='"+id+"']>label")[choosed?"addClass":"removeClass"]("choosed");
			};
		});
	}
	/**
	 * @description 获取选中的叶子
	 */
	Tree.prototype.getSelected=function () {
		//获取选中的员工
		var arr=[];
		this.selected.forEach(function(leaf){
			arr.push(leaf);
		})
		return arr;
	};
	/**
	 * @description 重置
	 * @param choosed 当前选择的叶子数组
	 */
	Tree.prototype.reset=function (choosed) {
		//重置当前选中的员工
		var that=this;
		this.selected=[];
//		var $selected=this.$tree.find(".selected");
//		$selected.removeClass("hasamount");
		this.leaves.forEach(function(leaf){
			if(leaf.beChoosed&&leaf.$name){
				leaf.$name.remove();
				that.$tree.find("[val='"+leaf.id+"']>label").removeClass("choosed");
				leaf.beChoosed=false;
				leaf.$name=null;
			};
		});
		if(choosed){
			var $name,
				$selected=this.$tree.find(".selected");
				
			choosed.forEach(function(leaf){
				$name=_getNameSpan(leaf);
				$selected.append($name);
				that.setLeafChoosed(leaf,true,$name);
			});
		}
		this.checkIsAll();
	};
	/**
	 * @description 跳转到某个枝干
	 */
	Tree.prototype.goTo=function (id) {
		var $current=this.$tree.find(".content>.active"),
			$target=$current.siblings();
			
		$target.children().html(this.getContent(id));
		J.Transition.run($current,$target,true);
		this.checkIsAll();
	};
	
	J.Tree=Tree;
}(J.$))
